# -*- coding: utf-8 -*-
# блядь ты заебал не ставить утф!!!!
import os,sys,time,cgi
from threading import Lock
import time,re
from re import match



from Cookie import SimpleCookie


class wsgiHandler():
    initLock=Lock()
    def __call__(self,environ,start_response):
        self.environ=environ
        start=time.time()
        headers=[]

        import logging
        #LOG_FILENAME = '/var/www/pycube.ru/httpdocs/logging_example.out'
        #logging.basicConfig(filename=LOG_FILENAME,level=logging.DEBUG,)

        '''        
        WSGI pycube handler.
        By nc
        nchanged@gmail.com        
        '''

        self.log=logging.debug

        #logging.debug(self.environ['PYCUBE_PROJECT'])
        #Setting python path
        #self.environ['PYCUBE_ROOT']=os.environ['PYCUBE_ROOT']
        #logging.debug(self.environ)
        self.path=self.set_path(self.environ['PYCUBE_PROJECT'])
        #self.set_path( self.environ['PYCUBE_PROJECT'] )



        #sys.path.append(self.environ['PYCUBE_PROJECT'])
        #sys.path.append(self.environ['PYCUBE_ROOT'])

        '''
        Glagne v opasnoste!
        Importing system init class       
        
        '''

        from pycube.core.engine import system_initialize
        conf=__import__(self.environ['PYCUBE_PROJECT_CONF'],
                        globals(),
                        locals(),[''],
                        -1)


        #logging.debug(self.environ['PYCUBE_PROJECT_CONF'])
        #logging.debug(dir(conf))     
        self.config=conf

        #try to reload system code
        if self.config.SYSTEM['MONITOR_CODE_CHANGE']:
            self.tracking_code_changes(monitor_inverval=0.1)

        '''        
        Trying to to get post data       
        '''
        form=False
        if self.is_post():
            form=self.get_post_form()
            self.post=self.collect_post_data(form)
        else:
            self.post=False



        '''
        Starting the system and the project world        
        '''
        #try:
        project_urls=__import__('%s.%s'%(self.environ['PYCUBE_PROJECT_NAME'],'url'),
                                       globals(),
                                       locals(),[''],-1)


        adv_tpl=None
        try:
            adv_tpl=project_urls.adv_tpl
        except:
            pass


        system=system_initialize(self.config,self.environ,self.post,form if form else False,urls=project_urls.urls,adv_tpl=adv_tpl)
        system_execution_time=system.start_the_world()

        '''
        Get The Server Response.
        Calculate response length
        '''

        response=system.response()

        if self.config.SYSTEM['MONITOR_SYSTEM_LOAD']:
            response=response+self.monitor_system_load(time.time()-start)

        system.set_header('Content-Length',len(response))
        system.set_header('Cache-Control','private, max-age=0')

        system.set_header('Expires','-1')

        if system.get_status_code():
            code=system.get_status_code()




        headers=system.get_headers()
        start_response(code,headers)


        return [ response ]


    def check_secure_cookie(self,environ):
        c=SimpleCookie(environ.get("HTTP_COOKIE",""))
        currentTime=time.time()
        if 'init' in c:
            cookieTime=float(c['init'].value)

            if (currentTime-cookieTime)<=0.4:
                return True
            else:
                return True
        else:
            return True

    def set_system_cookie(self):
        iCookie=SimpleCookie(self.environ.get("HTTP_COOKIE",""))
        iCookie['init']=str(time.time())
        iCookie['init']["expires"]=time.time()+13000000
        iCookie['init']["path"]="/"
        iCookie['init']["domain"]=""


        iCookieHeaders=match('^Set-Cookie:(.*?)$',str(iCookie),re.DOTALL)
        if iCookieHeaders:
            iCookieHeaders=iCookieHeaders.group(1)
            return ('Set-Cookie',iCookieHeaders)




    def set_path(self,path):
        """
        
        Setting site path. If any error accured, like
        invalid path, or path is not valid argument,
        exception will be raised
        
        """
        if isinstance(path,str):
            if os.path.isdir(path):
                if path not in sys.path:
                    sys.path.append(path)

                return path

            else:

                raise Exception('System was unable to find %s'%path)
        else:

            raise Exception('The path you set, is not a string. Check you system settings')


    def tracking_code_changes(self,monitor_inverval):
        '''
        
        Tracking for code changes.
        if needed - reload modules.
        Depends on settings key. Usefull for developing
        
        '''

        from pycube.core import monitor

        if self.config.SYSTEM.get('MONITOR_TRACK_INTERVAL'):
            monitor_inverval=self.config.SYSTEM['MONITOR_TRACK_INTERVAL']

        monitor.start(interval=0.1)
        monitor.track(self.path)

    def monitor_system_load(self,endTime):

        '''        
        Prints on page system load, usefull for track compicated requests,        
        and how it load the system        
        '''


        #data=open(self.path+'/pycube/handlers/monitor.tpl','r').read()
        # вано, и не пизди на меня за хардкодинг :) на свою data глянь
        data="""
        <style>
            #dmonitor{
                position:absolute; 
                padding:5px; 
                font-family:Arial, Helvetica, sans-serif; 
                font-size: 12px; 
                width: 200px; 
                color:white; 
                background-color:black; 
                bottom: 0; 
                left:0;
            }
        </style>
        <script>
        function setOpacity(value) {
            testObj=document.getElementById('dmonitor');
            testObj.style.opacity = value/10;
            testObj.style.filter = 'alpha(opacity=' + value*10 + ')';
        }
        </script>
        <div id="dmonitor" >
            <div onMouseOver="javascript:setOpacity(10)" onMouseOut="javascript:setOpacity(2)">SystemLoad: [sysload]</div>
        </div><script>setOpacity(2);</script>"""
        data=data.replace('[sysload]',str(endTime))

        return data#str(endTime)



    def is_post(self):
        '''
        Checking for post data
        
        '''

        if 'REQUEST_METHOD' in self.environ:
            if self.environ['REQUEST_METHOD']=='POST':
                return True
        return False


    def collect_post_data(self,form):

        '''        
        
        Collecting post data
        in dictionary.
        It will make comfort access to post values, 
        with no brain fucking
                
        '''



        fieldStorage={}

        try:
            for key  in form:
                fieldStorage[key]=form[key].value
        except:
            pass



        return fieldStorage


    def get_post_form(self):
        '''        
        
        Gettting wsgi post data
            
        '''
        input=self.environ['wsgi.input']
        post_form=self.environ.get('wsgi.post_form')
        if (post_form is not None
            and post_form[0] is input):

            return post_form[2]

        self.environ.setdefault('QUERY_STRING','')
        fs=cgi.FieldStorage(fp=input,
                              environ=self.environ,
                              keep_blank_values=1)

        return fs





application=wsgiHandler()


